<!--
  * 配送司机
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="4">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.name" placeholder="司机" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="联系电话" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.phone" placeholder="联系电话" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="在职状态" class="smart-margin-bottom0">
            <a-radio-group v-model:value="queryForm.job_status" @change="onSearch">
              <a-radio-button value="">全部</a-radio-button>
              <a-radio-button value="1">在职</a-radio-button>
              <a-radio-button value="2">离职</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="启用状态" class="smart-margin-bottom0">
            <a-radio-group v-model:value="queryForm.status" @change="onSearch">
              <a-radio-button value="">全部</a-radio-button>
              <a-radio-button value="1">启用</a-radio-button>
              <a-radio-button value="2">禁用</a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="add()" type="primary" v-privilege="'driver:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="deleteData(selectedRowKeyList)" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'driver:del'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>

        <a-button @click="showImportModal" primary v-privilege="'driver:import'">
          <template #icon>
            <ImportOutlined />
          </template>
          导入
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'driver:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'name'">
            <a @click="detail(record)">{{ text }}</a>
          </template>
          <template v-if="column.dataIndex === 'head_img'">
            <div class="smart-table-operate">
              <a-image :width="30" :src="text" />
            </div>
          </template>
          <template v-if="column.dataIndex === 'job_status'">
            <a-switch @click="modifyActionJob($event, record)" :loading="JobcheckLoading" :checked="record.job_status == 1 ? true : false" checked-children="在职" un-checked-children="离职" />
          </template>
          <template v-if="column.dataIndex === 'status'">
            <a-switch @click="modifyAction($event, record)" :loading="checkLoading" :checked="record.status == 1 ? true : false" checked-children="启用" un-checked-children="禁用" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c">详情</a-button>
              <!-- <a-button @click="add(record)" type="link" v-privilege="'driver:edit'">编辑</a-button>
              <a-button @click="changePasswordModal(true, record.id)" type="link" v-privilege="'driver:password'">修改密码</a-button>
              <a-button @click="deleteData(record.id, record.name)" danger type="link" v-privilege="'driver:del'">删除</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <ImportModal ref="importModalRef" @downloadExcel="driverApi.exportTpl" :import-excel="driverApi.importXlsx" @reloadList="queryData" />
    <DriverFormModal ref="formModal" @reloadList="queryData" />
    <!---------- 详情 begin ----------->
    <DriverDetailsModal ref="detailRef" />
    <!---------- 详情 end ----------->
    <!---------- 修改密码 ----------->
    <a-modal v-model:visible="showPasswordModal" title="修改密码" @ok="modifyPassword" :maskClosable="false">
      <a-form :model="passwordFormData" :rules="passwordRules" ref="passwordFormRef">
        <a-form-item label="新密码" name="password">
          <a-input v-model:value="passwordFormData.password" placeholder="请输入新密码" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import DriverDetailsModal from './components/driver-details-modal.vue'
import DriverFormModal from './components/driver-form-modal.vue'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { driverApi } from '@/api/business/data/driver-api'
import { PAGE_SIZE_OPTIONS } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import ImportModal from '@/components/support/import-modal/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
const appConfigStore = useAppConfigStore()
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '姓名',
    dataIndex: 'name'
  },
  {
    title: '头像',
    dataIndex: 'head_img'
  },
  {
    title: '联系电话',
    dataIndex: 'phone'
  },
  {
    title: '住址',
    dataIndex: 'address'
  },
  {
    title: '在职状态',
    dataIndex: 'job_status'
  },
  {
    title: '启用状态',
    dataIndex: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 120 : 130
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await driverApi.queryDriverList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await driverApi.delDriver({ id })
    return !!res
  },
  queryFormFilter: {
    name: '',
    phone: '',
    status: '',
    job_status: ''
  },
  queryFormOp: {
    name: QUERY_FORM_OP['模糊查询'],
    phone: QUERY_FORM_OP['模糊查询'],
    status: QUERY_FORM_OP['全等查询'],
    job_status: QUERY_FORM_OP['全等查询']
  }
})
onMounted(queryData)

// 选择表格行
const selectedRowKeyList = ref<number[]>([])

function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function add(goodsData) {
  formModal.value.showDrawer(goodsData)
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}
// ---------------------------- 修改状态 ----------------------------
const checkLoading = ref(false)
const modifyAction = async (checked, record) => {
  try {
    checkLoading.value = true
    const res = await driverApi.modifyDriver({
      id: record.id,
      field: 'status',
      value: checked == true ? 1 : 2
    })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    checkLoading.value = false
  }
}
const JobcheckLoading = ref(false)
const modifyActionJob = async (checked, record) => {
  try {
    JobcheckLoading.value = true
    const res = await driverApi.modifyDriver({
      id: record.id,
      field: 'job_status',
      value: checked == true ? 1 : 2
    })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    JobcheckLoading.value = false
  }
}
// ---------------------------- 修改密码 ----------------------------
const showPasswordModal = ref(false)
const passwordFormRef = ref()
const passwordFormData = ref({
  id: '',
  password: ''
})
const passwordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
}
function changePasswordModal(flag, id?: any) {
  showPasswordModal.value = flag
  flag && (passwordFormData.value.id = id)
  passwordFormRef.value.resetFields()
}
function modifyPassword() {
  passwordFormRef.value.validate().then(async () => {
    try {
      const res = await driverApi.modifyDriver({
        id: passwordFormData.value.id,
        field: 'password',
        value: passwordFormData.value.password
      })
      message.success(res.msg)
      changePasswordModal(false)
      queryData()
    } catch (e) {
      message.error(e.msg)
      errorSentry.captureError(e)
    }
  })
}
// ------------------------------- 导出和导入 ---------------------------------
const importModalRef = ref()
function showImportModal() {
  importModalRef.value.showImportModal()
}

// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp)
  }
  driverApi.exportXlsx(data)
}
</script>
